import { Camera, Color, Component, tween, _decorator, Sprite, UIOpacity, UITransform } from 'cc';
import Common from '../Config/Common';
import { GameEventType } from '../Event/EnumDefine';
import { EventManager } from '../Event/EventManager';
import { SoundManager, SoundType } from '../SoundManager';
const { ccclass, property } = _decorator;
/**
 * 摄像机闪红或自定义红色图片闪红
 */
@ccclass('FlashRedEffect')
export class FlashRedEffect extends Component {
  @property(Camera)
  mainCamera: Camera = null!; // 主摄像机

  @property(Sprite)
  redMask: Sprite = null; // 红色遮罩

  @property
  flashCount: number = 2; // 闪烁次数

  @property
  flashDuration: number = 0.5; // 总持续时间

  private originalColor: Color = new Color(0, 0, 0, 255); // 默认背景颜色
  private flashColor: Color = new Color(255, 0, 0, 225); // 闪红颜色

  onLoad() {
    // 保存摄像机的原始背景颜色
    this.originalColor = this.mainCamera.clearColor.clone();
    EventManager.instance.registerEvent(GameEventType.Flash_Red_Effect, this.onFlashRedEffect, this);

    this.onScreen();
    EventManager.instance.registerEvent(GameEventType.Screen_Change, this.onScreen, this);
  }

  onScreen() {
    let size = Common.instance.getScreenSize();
    this.redMask.node.getComponent(UITransform).setContentSize(size.width, size.height);
  }

  onFlashRedEffect() {
    this.onFlashSprite();
  }

  /**
   * 摄像机闪红效果
   * @param duration 每次闪红的持续时间（秒）
   * @param interval 每次闪红之间的间隔时间（秒）
   * @param repeat 闪红次数
   */
  onFlashScreen(
    duration: number = 0.15,
    interval: number = 0.1,
    repeat: number = 3,
  ) {
    for (let i = 0; i < repeat; i++) {
      // 计算每次闪红的延迟时间
      const delay = i * (duration * 2 + interval);

      // 闪红效果：从原始颜色到红色，再回到原始颜色
      tween(this.mainCamera)
        .delay(delay) // 延迟
        .to(duration, { clearColor: this.flashColor }) // 变为红色
        .to(duration, { clearColor: this.originalColor }) // 恢复原始颜色
        .start();
    }
  }

  /** 图闪红 */
  onFlashSprite() {
    const singleFlashDuration = this.flashDuration / (2 * this.flashCount); // 单次闪烁的持续时间
    SoundManager.instance.playSound(SoundType.Waring);
    // 创建闪烁动画
    let flashTween = tween(this.redMask.node.getComponent(UIOpacity))
      .repeat(this.flashCount, // 重复次数
        tween()
          .to(singleFlashDuration, { opacity: 255 }) // 渐显
          .to(singleFlashDuration, { opacity: 0 }) // 渐隐
          .delay(0.5)
      );

    // 执行动画
    flashTween.start();
  }

}
